package com.netcracker.lab1.socket;

/**
 * Created with IntelliJ IDEA.
 * User: nocturne
 * Date: 02.02.13
 * Time: 21:12
 * To change this template use File | Settings | File Templates.
 */
import com.netcracker.lab1.controller.MusicTrackController;
import com.netcracker.lab1.model.AbstractMusicTrackManager;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Calendar;

public class Server {

    private static final MusicTrackController mtc = new MusicTrackController();
    private int port;

    public Server(int p) {
        port = p;
    }

/*    public static void main(String[] args) throws IOException, ClassNotFoundException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Server s = new Server(Integer.valueOf(br.readLine()));
        s.start();
    }*/

    public void start() throws IOException, ClassNotFoundException {
        ServerSocket ss = new ServerSocket(port);
        System.out.println("Server: started");
        while (true) {
            Socket s = ss.accept();
            new RequestThread(s).start();
            System.out.println(Calendar.getInstance().getTime().toString() + " " + "Server: new client connected is ip: " + s.getRemoteSocketAddress());
        }
    }

    private class RequestThread extends Thread {

        private Socket s;

        private RequestThread(Socket s) {
            this.s = s;
        }

        public void run() {
            try {
                //DataOutputStream out = new DataOutputStream(s.getOutputStream());
               // DataInputStream in = new DataInputStream(s.getInputStream());

                ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
                ObjectInputStream in = new ObjectInputStream(s.getInputStream());

/*                int val1, val2, result;

                val1 = (int) in.readInt();
                System.out.println("Server: read new object " + val1 + " from " + s.toString());

                val2 = (int) in.readInt();
                System.out.println("Server: read new object " + val2 + " from " + s.toString());

                result = val1 + val2;

                out.writeInt(result);
                out.flush();
                System.out.println("Server: sent result object " + result + " to " + s.toString());*/

                //MusicTrackController mtc = new MusicTrackController();
                String[] command1 = null;

                try {
                    command1 = (String[])in.readObject();
                } catch (ClassNotFoundException e) {
                    System.out.println(e);
                }

                System.out.println("command " + command1[0]);

                String val = "";
                String json = null;
                String jsonresult = null;

                if(command1[0].equals("findTrackById")) {
                    if(mtc.getSizeLibrary() > Integer.parseInt(command1[1]))  {
                        val =  mtc.findTrackById(Integer.parseInt(command1[1])).getAuthor() + " - " + mtc.findTrackById(Integer.parseInt(command1[1])).getTitle();
                    } else {
                        val = "no result by id " + command1[1];
                    }

                }  else if(command1[0].equals("findByAuthor")) {
                    //System.out.println("findByAuthor " + mtc.getSizeLibrary());
                    for(int i = 0; i < mtc.getSizeLibrary(); i++) {
                        try {
                            if(mtc.findTrackById(i).getAuthor().equals(command1[1])) {
                                val += "{ \"id\": \""+i+"\", \"author\": \""+mtc.findTrackById(i).getAuthor()+"\", \"title\": \""+mtc.findTrackById(i).getTitle()+"\", \"album\": \""+mtc.findTrackById(i).getAlbum()+"\", \"duration\": \""+mtc.findTrackById(i).getDuration()+"\", \"genre\": \""+mtc.findTrackById(i).getGenre()+"\" },";
                            }
                        } catch (NullPointerException e) {
                            System.out.println("findByAuthor " + e);
                        }
                    }

                    if(val.length()-1 >= 0) {
                        json = "[" + val.substring(0, val.length()-1) + "]";
                    } else {
                        val = "{ \"id\": \"no result\", \"author\": \"no result\", \"title\": \"no result\", \"album\": \"no result\", \"duration\": \"0\", \"genre\": \"0\" }";
                        json = "[" + val.substring(0, val.length()) + "]";
                    }

                }  else if(command1[0].equals("createNewTrack")) {

                    ArrayList<JSONObject> obj2 = new ArrayList<JSONObject>();
                    Object obj = JSONValue.parse(command1[1].toString());
                    JSONArray arrayJson = (JSONArray) obj;


                    for (int i = 0; i < arrayJson.size(); i++) {
                        obj2.add((JSONObject) arrayJson.get(i));
                        //System.out.println(obj2.get(i).get("author") + " - " + obj2.get(i).get("title"));
                    }

                    System.out.println("Server: json " + command1[1].toString());

                    for (int i = 0; i < arrayJson.size(); i++) {
                        mtc.createMusicTrack(mtc.getSizeLibrary(), obj2.get(i).get("title").toString(),obj2.get(i).get("author").toString(), obj2.get(i).get("album").toString(), Integer.parseInt(obj2.get(i).get("genre").toString()), Integer.parseInt(obj2.get(i).get("duration").toString()));

                    }

                    //val =  "{ \"create track\": \"Status OK!\" }";

                }  else if(command1[0].equals("deleteTrack")) {
                    System.out.println(mtc.getSizeLibrary());
                    mtc.deleteTrackInLibraryById(Integer.parseInt(command1[1]));
                    System.out.println(mtc.getSizeLibrary());


                }  else if(command1[0].equals("saveOnServer")) {
                    mtc.saveMusicTrack("c://trackLibraryNetcracker.out");

                }  else if(command1[0].equals("openOnServer")) {
                    try {
                        mtc.openMusicTrack("c://trackLibraryNetcracker.out");
                    } catch (ClassNotFoundException e) {
                        System.out.println(e);
                    }

                }  else {
                    val = "{ \"id\": \"no result\", \"author\": \"no result\", \"title\": \"no result\", \"album\": \"no result\", \"duration\": \"no result\", \"genre\": \"no result\" }";
                    json = "[" + val.substring(0, val.length()-1) + "]";
                }

                out.writeObject(json);
                in.close();
                out.close();

                if(command1[0].equals("close")) {
                    s.close();
                }

                s.close();

            } catch (IOException e) {
                System.err.println("Server: Exception : " + e.toString());
            }
        }
    }
}


